package com.example.demosecurityjwt.service.impl;

import com.example.demosecurityjwt.pojo.JUser;
import com.example.demosecurityjwt.pojo.JwtUserFactory;
import com.example.demosecurityjwt.pojo.UserDto;
import com.example.demosecurityjwt.pojo.entity.TbUser;
import com.example.demosecurityjwt.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @Author: bysun
 * @Date: 2019/3/28 16:22
 */
@Service
public class userDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TbUser user = userService.getUserByName(username);
        UserDto userDto = new UserDto();
        BeanUtils.copyProperties(user, userDto);

        if (user == null) {
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
        } else {
            return JwtUserFactory.create(userDto);
        }
    }
}
